package controller;

import generator.MissionGenerator;

import java.awt.Point;
import java.util.ArrayList;

import mission.Mission;
import mission.MissionStep;



public class MissionEngine {
	
	public MissionEngine(){
		Mission m = null;
		if(LocalManager.getCurrentMission() == null){
			m = MissionGenerator.next();
			LocalManager.setCurrentMission(m);
		}
		MissionStep cur = LocalManager.getCurrentMission().getCurrentMissionStep();
		if(cur == null){
			possibleStep = new ArrayList<MissionStep>();
			possibleStep.add(LocalManager.getCurrentMission().getStarter());
		}else
			possibleStep = cur.getNext();
		oldLocation = null;
		inProgress = false;
		oldStep = null;
	}
	
	public void choseStep(int index){
		if(!inProgress){
			Mission m = LocalManager.getCurrentMission();
			oldLocation = LocalManager.getPlayerLocation();
			oldStep = m.getCurrentMissionStep();
			
			m.setCurrentMissionStep(possibleStep.get(index));
			LocalManager.setPlayerLocation(m.getCurrentMissionStep().getLocation());
			inProgress = true;
		}
	}
	
	public void stepFinish(){
		if(inProgress){
			if(LocalManager.getCurrentMission().isFinished()){
				//reward
				LocalManager.setCurrentMission(MissionGenerator.next());
			}
			MissionStep cur = LocalManager.getCurrentMission().getCurrentMissionStep();
			if(cur == null){
				possibleStep = new ArrayList<MissionStep>();
				possibleStep.add(LocalManager.getCurrentMission().getStarter());
			}else
				possibleStep = cur.getNext();
			inProgress = false;
		}
	}
	
	public void undoStep(){
		if(inProgress){
			LocalManager.setPlayerLocation(oldLocation);
			oldLocation = null;
			LocalManager.getCurrentMission().setCurrentMissionStep(oldStep);
			oldStep = null;
			inProgress = false;
		}
	}
	
	public Point getPlayerLocation(){
		return LocalManager.getPlayerLocation();
	}
	
	public Mission getCurrentMission() {
		return LocalManager.getCurrentMission();
	}

	public MissionStep getCurrentStep() {
		return LocalManager.getCurrentMission().getCurrentMissionStep();
	}

	public ArrayList<MissionStep> getPossibleStep() {
		return possibleStep;
	}

	private MissionStep oldStep;
	private ArrayList<MissionStep> possibleStep;
	private Point oldLocation;
	private boolean inProgress;
}
